/*
 * Copyright 2011-2012 by The Regents of the University of California Licensed
 * under the Apache License, Version 2.0 (the "License"); you may not use this
 * file except in compliance with the License. you may obtain a copy of the
 * License from
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package edu.ucsd.db.bassarisk.indexer.hyracks;

import java.nio.ByteBuffer;

import edu.uci.ics.hyracks.api.context.IHyracksTaskContext;
import edu.uci.ics.hyracks.api.dataflow.IOperatorNodePushable;
import edu.uci.ics.hyracks.api.dataflow.value.IRecordDescriptorProvider;
import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
import edu.uci.ics.hyracks.api.job.JobSpecification;
import edu.uci.ics.hyracks.dataflow.common.comm.io.FrameTupleAppender;
import edu.uci.ics.hyracks.dataflow.std.base.AbstractSingleActivityOperatorDescriptor;
import edu.uci.ics.hyracks.dataflow.std.base.AbstractUnaryInputUnaryOutputOperatorNodePushable;
import edu.ucsd.db.bassarisk.indexer.api.IPosting.IPositionedPosting;
import edu.ucsd.db.bassarisk.indexer.api.IPosting.ISequencedPosting;
import edu.ucsd.db.bassarisk.indexer.api.IPostingHandler;
import edu.ucsd.db.bassarisk.indexer.api.IStageTwoAnalyzerFactory;
import edu.ucsd.db.bassarisk.indexer.hyracks.HyracksPostingSerialization.IPostingTupleReader;
import edu.ucsd.db.bassarisk.indexer.hyracks.HyracksPostingSerialization.IPostingTupleWriter;
import edu.ucsd.db.bassarisk.indexer.impl.Positioner;
import edu.ucsd.db.bassarisk.indexer.impl.PostingFactory;

public class IndexerStageTwoOperatorDescriptor extends
    AbstractSingleActivityOperatorDescriptor {
  private static final long serialVersionUID = -6699096379245477987L;
  private final IStageTwoAnalyzerFactory[] analyzers;

  public IndexerStageTwoOperatorDescriptor(final JobSpecification spec,
                                           final IStageTwoAnalyzerFactory[] analyzers) {
    super(spec, 1, 1);
    this.analyzers = analyzers;
  }

  @Override
  public IOperatorNodePushable
      createPushRuntime(final IHyracksTaskContext ctx,
                        final IRecordDescriptorProvider recordDescProvider,
                        final int partition, final int nPartitions)
          throws HyracksDataException {

    FrameTupleAppender appender = new FrameTupleAppender(ctx.getFrameSize());
    final IPostingTupleWriter<IPositionedPosting> postingWriter =
        HyracksPostingSerialization.createPositionedPostingTupleWriter(ctx
            .allocateFrame(), appender);
    IPostingHandler<IPositionedPosting> postingSink = postingWriter;
    // Iterate backwards over the analyzers to build the proper analysis
    // pipeline.
    for (int i = (this.analyzers.length - 1); i >= 0; ++i) {
      IStageTwoAnalyzerFactory factory = this.analyzers[i];
      postingSink = factory.createAnalyzer(postingSink, PostingFactory.INSTANCE);
    }
    // At the top of the pipeline is an operator which decides what position to
    // assign to each posting
    Positioner positioner = new Positioner(postingSink, PostingFactory.INSTANCE);
    final IPostingTupleReader<ISequencedPosting> postingDeserializer =
        HyracksPostingSerialization.createSequencedPostingTupleReader(ctx
            .getFrameSize(), positioner, PostingFactory.INSTANCE);

    return new AbstractUnaryInputUnaryOutputOperatorNodePushable() {
      @Override
      public void close() throws HyracksDataException {
        postingWriter.close();
        this.writer.close();
      }

      @Override
      public void fail() throws HyracksDataException {
        this.writer.fail();
      }

      @Override
      public void nextFrame(final ByteBuffer buffer) throws HyracksDataException {
        postingDeserializer.nextFrame(buffer);
      }

      @Override
      public void open() throws HyracksDataException {
        this.writer.open();
        postingWriter.setFrameWriter(this.writer);
      }
    };
  }
}
